<?php

namespace App\Http\Controllers;

use App\Models\AdminRoleUserModel;
use App\Models\AdminUserModel;
use App\Models\yb\RequestUrlModel;
use App\Models\yb\UserModel;
use Encore\Admin\Facades\Admin;
use Illuminate\Support\Facades\Hash;
use Illuminate\Http\Request;
use EasyWeChat\Factory;
use Tymon\JWTAuth\Facades\JWTFactory;
use Tymon\JWTAuth\Facades\JWTAuth;
use Illuminate\Support\Facades\Log;



class AuthController extends Controller
{
    /**
     * Create a new AuthController instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth:api', ['except' => ['login', 'refresh','auth','NetworkAuth','NetworkRegister','NetworkAuthLogin','douyinAuth']]);
    }

    /**
     * Get a JWT via given credentials.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function login(Request $request)
    {

        $credentials = request(['username', 'password']);

        if (!$token = auth('api')->attempt($credentials)) {
            return response()->json(['code'=>'201','msg' => '账号或密码错误']);
        }

        $data =  $this->respondWithToken($token);
        $member_sub = response()->json(auth('api')->user());
        $list = $data->original;

        $user_list =  $member_sub->original;
        if($user_list['status'] != 1){
            return response()->json(['code'=>'203','msg' => '用户已被禁用']);
        }
        $user_list['avatar'] = env('OSS_URL').$user_list['avatar'];

        $list['user_list'] = $user_list;
        return response()->json(['code'=>'200','msg' => '登录成功','data'=>$list]);

    }
    /**
     * Get a JWT via given credentials.
     * 商家登录
     * @return \Illuminate\Http\JsonResponse
     */
    public function NetworkAuth(Request $request){

        $user_id = $request->post('user_id');

        $user_data = AdminUserModel::where(['id' => $user_id])->first();

        if (empty($user_data) || empty($user_id)) {
            return response()->json(['code' => '401', 'msg' => '请登录']);
        }

        $avatar_str = mb_substr($user_data['avatar'],0,4);
        if($avatar_str != 'http'){
            $user_data['avatar'] = env('OSS_URL').$user_data['avatar'];
        }

        return response()->json(['code' => '200', 'msg' => '登录成功','data'=>$user_data]);

    }

    public function NetworkAuthLogin(Request $request)
    {

        $code = $request->post('code');
        $user_id = $request->post('user_id');

        $config = [
            'app_id' => env('NETWORK_WECHAT_CLIENT_APP_ID'),  // 这里需要自行修改
            'secret' => env('NETWORK_WECHAT_CLIENT_APP_SECRET'),  // 这里需要自行修改
        ];

        $app = Factory::miniProgram($config);

        $data = $app->auth->session($code);

        //判断code是否过期
        if (isset($data['errcode'])) {
            return response()->json(['code' => '203', 'msg' => 'code已过期或不正确']);
        }

        $admin_user = AdminUserModel::where(['id' => $user_id])->first();
        if(empty($admin_user)){
            return response()->json(['code' => '401', 'msg' => '请登录']);
        }

        if(empty($admin_user['openid'])){
            AdminUserModel::where(['id'=>$user_id])->update([
                    'openid' => $user_id,
                    'openids' => $data['openid'],
                ]
            );
        }

        $admin_user = AdminUserModel::where(['id' => $user_id])->first();


        return response()->json(['code' => '200', 'msg' => '授权成功','data'=>$admin_user]);

    }

    /**
     * Get a JWT via given credentials.
     * 商家注册
     * @return \Illuminate\Http\JsonResponse
     */
    public function NetworkRegister(Request $request){

        $name = $request->post('name');
        if(empty($name)){
            return response()->json(['code'=>'203','msg' => '网点名称不能为空']);
        }

        $avatar = $request->post('avatar');
        if(empty($avatar)){
            return response()->json(['code'=>'203','msg' => '请上传头像']);
        }

        $username = $request->post('username');
        if(empty($username)){
            return response()->json(['code'=>'203','msg' => '账户手机号不能为空']);
        }

        $mobile = $request->post('mobile');
        if(empty($mobile)){
            return response()->json(['code'=>'203','msg' => '网点联系电话不能为空']);
        }

        $distribution_scope = $request->post('distribution_scope');
        if(empty($distribution_scope)){
            return response()->json(['code'=>'203','msg' => '配送范围不能为空']);
        }

        $address = $request->post('address');
        if(empty($address)){
            return response()->json(['code'=>'203','msg' => '网点地址不能为空']);
        }

        $latitude = $request->post('latitude');
        if(empty($latitude)){
            return response()->json(['code'=>'203','msg' => '纬度不能为空']);
        }

        $longitude = $request->post('longitude');
        if(empty($longitude)){
            return response()->json(['code'=>'203','msg' => '经度不能为空']);
        }

        $password = $request->post('password');
        if(empty($password)){
            return response()->json(['code'=>'203','msg' => '登录密码不能为空']);
        }

        $confirm_password = $request->post('confirm_password');
        if(empty($confirm_password)){
            return response()->json(['code'=>'203','msg' => '确认密码不能为空']);
        }

        if($password != $confirm_password){
            return response()->json(['code'=>'203','msg' => '两次输入密码不一致']);
        }

        $admin_user_data = AdminUserModel::where(['username'=>$username])->first();

        if(!empty($admin_user_data)){
            return response()->json(['code'=>'203','msg' => '该账号已注册']);
        }

        $admin_id = AdminUserModel::insertGetId([
            'name' => $name,
            'avatar' => $avatar,
            'username' => $username,
            'mobile' => $mobile,
            'distribution_scope' => $distribution_scope,
            'address' => $address,
            'latitude' => $latitude,
            'longitude' => $longitude,
            'password' => Hash::make($password),
            'type' => 2,
            'created_at' => date('Y-m-d H:i:s',time())
        ]);

        AdminRoleUserModel::insert([
            'role_id'=>30,
            'user_id'=>$admin_id
        ]);

        $user_data = AdminUserModel::where(['id'=>$admin_id])->first();

        $avatar_str = mb_substr($user_data['avatar'],0,4);
        if($avatar_str != 'http'){
            $user_data['avatar'] = env('OSS_URL').$user_data['avatar'];
        }

        return response()->json(['code' => '200', 'msg' => '登录成功','data'=>$user_data]);

    }
    /*
    * 用户登录
    */
    public function auth(Request $request)
    {
        log::info($request->input());
        $code = $request->post('code');
        $rawData = $request->post('rawData');
        $iv= $request->post('iv');
        $encryptedData= $request->post('encryptedData');
        $inviter_user_id = $request->post('inviter_openid');

        $config = [
            'app_id' => env('WECHAT_CLIENT_APP_ID'),  // 这里需要自行修改
            'secret' => env('WECHAT_CLIENT_APP_SECRET'),  // 这里需要自行修改
        ];

        $app = Factory::miniProgram($config);

        $data = $app->auth->session($code);

        $phone_data = $app->encryptor->decryptData($data['session_key'], $iv, $encryptedData);


        //判断code是否过期
        if (isset($data['errcode'])) {
            return response()->json(['code' => '203', 'msg' => 'code已过期或不正确']);
        }
        $weappOpenid = $data['openid'];
        $weixinSessionKey = $data['session_key'];

        $wechat = json_decode($rawData, true);

        $user = UserModel::where(['openid' => $weappOpenid])->first();


        if(empty($user)){
            $data = [
                    'openid' => $weappOpenid,
                    'nickname' => $wechat['nickName'],
                    'avatar' => $wechat['avatarUrl'],
                    'session_key' => $weixinSessionKey,
                    'phone' => $phone_data['phoneNumber'],
                    'channel' => 1,
                    'created_at'=>date('Y-m-d H:i:s',time())
                ];
            if(!empty($inviter_user_id)){
                $inviter_user = UserModel::where(['id' => $inviter_user_id])->first();
                if(!empty($inviter_user)){
                    $data['inviter_user_openid'] = $inviter_user['openid'];
                    $data['inviter_user_id'] = $inviter_user_id;
                }
            }    
            UserModel::insert($data);
            $user = UserModel::where(['openid' => $weappOpenid])->first();
        }

        if($user['status']!=1){
            return response()->json(['code' => '203', 'msg' => '用户已被禁用']);
        }

        $customClaims = ['sub' => ["openid" => $user['openid'], 'session_key' => $user['session_key']]];
        $payload = JWTFactory::customClaims($customClaims)->make();

        if (!$token = JWTAuth::encode($payload)->get()) {
            return ['code' => 401, 'massage' => 'Unauthorized'];
        }

        $data['token'] = $token;
        $data['user'] =  $user;

        return response()->json(['code' => '200', 'msg' => '登录成功','data'=>$data]);

    }

    /*
   * 用户登录
   */
    public function douyinAuth(Request $request)
    {

        $code = $request->post('code');
        $nickname = $request->post('nickname');
        $avatarUrl = $request->post('avatarUrl');
        $phoneNumber = $request->post('phoneNumber');

        $client =new \GuzzleHttp\Client();

        $res = $client->request('POST','https://developer.toutiao.com/api/apps/v2/jscode2session',[
            'json'=>[
                'appid'=>env('DOUYIN_CLIENT_APP_ID'),
                'secret'=>env('DOUYIN_CLIENT_APP_SECRET'),
                'code'=>$code,
            ],
            'headers' => ['Content-type'=> 'application/json']
        ]);
        $datas = json_decode((string)$res->getBody(), true);

        //判断code是否过期
        if ($datas['err_no']>0) {
            return response()->json(['code' => '203', 'msg' => 'code已过期或不正确']);
        }
        $openid = $datas['data']['openid'];
        $sessionKey = $datas['data']['session_key'];

        $user = UserModel::where(['openid' => $openid])->first();

        if(empty($user)){
            UserModel::insert([
                    'openid' => $openid,
                    'nickname' => $nickname,
                    'avatar' => $avatarUrl,
                    'session_key' => $sessionKey,
                    'phone' => $phoneNumber,
                    'channel' => 2,
                    'created_at'=>date('Y-m-d H:i:s',time())
                ]
            );
            $user = UserModel::where(['openid' => $openid])->first();
        }

        if($user['status']!=1){
            return response()->json(['code' => '203', 'msg' => '用户已被禁用']);
        }

        $customClaims = ['sub' => ["openid" => $user['openid'], 'session_key' => $user['session_key']]];

        $payload = JWTFactory::customClaims($customClaims)->make();

        if (!$token = JWTAuth::encode($payload)->get()) {
            return ['code' => 401, 'massage' => 'Unauthorized'];
        }

        $data['token'] = $token;
        $data['user'] =  $user;
        $data['openid'] =  $openid;

        return response()->json(['code' => '200', 'msg' => '登录成功','data'=>$data]);

    }


    /**
     * Log the user out (Invalidate the token).
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function logout()
    {
        auth('api')->logout();

        return response()->json(['code'=>'200','msg' => '退出成功','data'=>array()]);

    }

    /**
     * Refresh a token.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function refresh()
    {
        return $this->respondWithToken(auth('api')->refresh());
    }

    /**
     *
     * Get the token array structure.
     * @param  string $token
     *
     * @return \Illuminate\Http\JsonResponse
     */
    protected function respondWithToken($token)
    {
        return response()->json([
            'access_token' => $token,
            'token_type' => 'Bearer',
            'expires_in' => auth('api')->factory()->getTTL() * 60
        ]);
    }

    /**
     * 修改密码
     *
     * @param  string $token
     *
     * @return \Illuminate\Http\JsonResponse
     */
    protected function changePwd()
    {

        $member_sub = response()->json(auth('api')->user());
        $member_list = $member_sub->original;

        $credentials = request(['original_pwd', 'new_pwd','confim_new_pwd']);
        if(empty($credentials['original_pwd'])){
            return response()->json(['code'=>'201','msg' => '请输入原密码']);
        }
        if(empty($credentials['new_pwd'])){
            return response()->json(['code'=>'201','msg' => '请输入新密码']);
        }
        if(empty($credentials['confim_new_pwd'])){
            return response()->json(['code'=>'201','msg' => '请确认新密码']);
        }

        if($credentials['confim_new_pwd']!=$credentials['new_pwd']){
            return response()->json(['code'=>'201','msg' => '两次密码输入不一致']);
        }

        if(!Hash::check($credentials['original_pwd'],$member_list['password'])){
            return response()->json(['code'=>'201','msg' => '原密码错误，请重新输入']);
        }

        AdminUserModel::where(['id'=>$member_list['id']])->update([
            'password' => Hash::make($credentials['confim_new_pwd'])
        ]);

        return response()->json(['code'=>'200','msg' => '修改成功','data'=>array()]);

    }

    /**
     * 修改头像
     *
     * @param  string $token
     *
     * @return \Illuminate\Http\JsonResponse
     */
    protected function upd_me()

    {

        $member_sub = response()->json(auth('api')->user());
        $member_list = $member_sub->original;

        $credentials = request(['avatar']);

        AdminUserModel::where(['id'=>$member_list['id']])->update([
            'avatar' => $credentials['avatar']
        ]);

        return response()->json(['code'=>'200','msg' => '修改成功','data'=>array()]);

    }

}
